﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class enemymanager : MonoBehaviour
{
    //方向
    private float h, v;
    private int flag;
    //引用
    public float speed;
    public GameObject bullet;
    public GameObject explosion;
    private SpriteRenderer sr;
    public Sprite[] enemys;
    public AudioClip Ac;
    //计时器
    public float cooldown;
    private float cdtiming;
    public float mvcooldown;
    private float mvcdtiming;
    

    private void Awake()
    {
        sr = GetComponent<SpriteRenderer>();
    }
    void Start()
    {
        mvcdtiming = mvcooldown;
        h = 0;
        v = -1;
        cdtiming = cooldown;
    }
    private void FixedUpdate()
    {
        if (mvcdtiming > 0) mvcdtiming -= Time.fixedDeltaTime;
        changemove();
        move();
    }

    void Update()
    {

        if (cdtiming > 0) cdtiming -= Time.deltaTime;
        
        change();
        attack();
    }

    private void move()
    {
        transform.Translate(new Vector3(0, speed * Time.fixedDeltaTime * v, 0));
        if (v > 0.5f) flag = 0;
        if (v < -0.5f) flag = 2;
        transform.Translate(new Vector3(speed * Time.fixedDeltaTime * h, 0, 0));
        if (h > 0.5f) flag = 1;
        if (h < -0.5f) flag = 3;
    }
    private void attack()
    {
        if (cdtiming > 0) return;
        Instantiate(bullet, transform.position, Quaternion.Euler(0, 0, -90 * flag));
        AudioSource.PlayClipAtPoint(Ac, transform.position);
        cdtiming = cooldown;
    }
    private void change()
    {
        sr.sprite = enemys[flag];
    }
    public void damaged()
    {
        Instantiate(explosion, transform.position, Quaternion.Euler(0, 0, 0));
        Destroy(gameObject);
    }
    private void changemove()
    {
        if (mvcdtiming > 0) return;
        int num = Random.Range(0, 8);
        if (num > 4)
        {
            v = -1;
            h = 0;
        }
        else if (num == 0)
        {
            v = 1;
            h = 0;
        }
        else if (num == 1 || num == 2)
        {
            v = 0;
            h = -1;
        }
        else
        {
            v = 0;
            h = 1;
        }
        mvcdtiming = mvcooldown;
    }
}
